package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.constants.RedisConstants.CACHE_SHOP_TYPE_KEY;
import static com.hmdp.constants.RedisConstants.CACHE_SHOP_TYPE_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @since 2023-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public List<ShopType> queryAllType() {
        String key= String.valueOf(CACHE_SHOP_TYPE_KEY);
        String shopTypeList = stringRedisTemplate.opsForValue().get(key);
        if(shopTypeList != null && !shopTypeList.isEmpty()){
            //缓存中存在直接返回
            log.debug("从缓存中读取到商铺列表");
            return JSONUtil.toList(shopTypeList, ShopType.class);
        }
        //不存在，从数据库中查询
        List<ShopType> sortShop = query().orderByAsc("sort").list();
        if(shopTypeList == null) {
            log.debug("将商铺列表缓存");
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(sortShop), CACHE_SHOP_TYPE_TTL, TimeUnit.MINUTES);
        }
        return sortShop;
    }
}
